class FileUtil {
  /**
     * 选择文件
     * @param {String} accept
     * @param {boolean} multiple
     * @returns {Promise}
     */
  getFile (obj) {
    obj.accept = obj.accept || 'image/*';
    let inputFile = this.createInputFile(obj.accept, obj.multiple);
    inputFile.onchange = eve => {
      obj.multiple ? obj.done(eve.path[0].files, eve.path[0])
        : this.fileReaders(eve.path[0].files[0]).then(url => {
          typeof obj.done === 'function' && obj.done(eve.path[0].files[0], url, eve.path[0]);
        }).catch(err => {
          console.error(err);
        });
    };
    inputFile.click();
  }
  /**
     * create input file's element
     * @param {String} accept
     * @param {boolean} multiple
     * @returns {Element}
     */
  createInputFile (accepts, multiple) {
    let inputFile = null;
    if (typeof document.createElement !== 'function') { /* IE8以下 */
      multiple ? inputFile = document.createElement(`<input type="file" accept="${accepts}">`)
        : inputFile = document.createElement(`<input type="file" accept="${accepts}" multiple>`);
    } else {
      inputFile = document.createElement('input');
      inputFile.type = 'file';
      inputFile.accept = accepts;
      inputFile.multiple = multiple ? 'true' : '';
    }
    return inputFile;
  }
  /**
     * 文件处理
     * @param {File} file
     * @param {String} type
     */
  fileReaders (file, type) {
    var reader = new FileReader();
    switch (type) {
      case 'binary': reader.readAsBinaryString(file);/* 二进制编码 */ break;
      case 'text': reader.readAsText(file, 'gb2312');/* 文本 */ break;
      case 'url': reader.readAsDataURL(file);/* url */ break;
      default: reader.readAsDataURL(file);/* url */ break;
    }
    return new Promise((resolve, reject) => {
      reader.onload = event => {
        resolve(event.target.result);
      };
      reader.onerror = function () {
        reject(new Error(false));
      };
    });
  }
  getFileUrl (file) {
    var url = null;
    if (window.createObjectURL !== undefined) { // basic
      url = window.createObjectURL(file);
    } else if (window.URL !== undefined) { // mozilla(firefox)
      url = window.URL.createObjectURL(file);
    } else if (window.webkitURL !== undefined) { // webkit or chrome
      url = window.webkitURL.createObjectURL(file);
    }
    return url;
  }
}
export default new FileUtil();
